import { ref, computed } from 'vue'

export function useLayers(getCanvas) {
  const layers = ref([])

  // 更新图层列表
  const updateLayers = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    layers.value = fabricCanvas.getObjects().map((obj, index) => ({
      id: obj.id || `layer-${index}`,
      type: obj.type,
      visible: !obj.hidden,
      locked: obj.locked,
      object: obj
    }))
  }

  // 监听画布变化
  const initLayerObserver = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    fabricCanvas.on('object:added', updateLayers)
    fabricCanvas.on('object:removed', updateLayers)
    fabricCanvas.on('object:modified', updateLayers)
  }

  // 切换图层可见性
  const toggleLayerVisibility = (layerId) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      layer.object.set('visible', !layer.object.visible)
      layer.visible = !layer.visible
      fabricCanvas.renderAll()
    }
  }

  // 锁定/解锁图层
  const toggleLayerLock = (layerId) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      layer.object.set('locked', !layer.object.locked)
      layer.locked = !layer.locked
      fabricCanvas.renderAll()
    }
  }

  // 删除图层
  const deleteLayer = (layerId) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      fabricCanvas.remove(layer.object)
      fabricCanvas.renderAll()
    }
  }

  // 调整图层顺序
  const reorderLayer = (layerId, direction) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const layer = layers.value.find(l => l.id === layerId)
    if (!layer) return

    if (direction === 'up') {
      fabricCanvas.bringForward(layer.object)
    } else if (direction === 'down') {
      fabricCanvas.sendBackwards(layer.object)
    } else if (direction === 'top') {
      fabricCanvas.bringToFront(layer.object)
    } else if (direction === 'bottom') {
      fabricCanvas.sendToBack(layer.object)
    }

    updateLayers()
  }

  // 复制图层
  const duplicateLayer = (layerId) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const layer = layers.value.find(l => l.id === layerId)
    if (layer) {
      layer.object.clone((cloned) => {
        cloned.set({
          left: cloned.left + 20,
          top: cloned.top + 20
        })
        fabricCanvas.add(cloned)
        fabricCanvas.setActiveObject(cloned)
        fabricCanvas.renderAll()
      })
    }
  }

  return {
    layers,
    initLayerObserver,
    updateLayers,
    toggleLayerVisibility,
    toggleLayerLock,
    deleteLayer,
    reorderLayer,
    duplicateLayer
  }
} 